package cn.kgc.spring04.proxy;

import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/2/21
 * @Description:
 */
public class CglibProxy {

    private Object target;

    public CglibProxy(Object object){
        this.target= object;
    }

    public Object getProxy(){

        Enhancer enhancer = new Enhancer();

        // 设置类加载器
        enhancer.setClassLoader(CglibProxy.class.getClassLoader());

        // 设置被代理对象
        enhancer.setSuperclass(target.getClass());

        // 传递一个能编写功能增强的对象

        MethodInterceptor methodInterceptor = new MethodInterceptor() {

            //Method method  通过代理对象调用的方法   目标对象中的方法
            //Object[] objects  方法的参数
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                System.out.println("----------cglib log-----------");

                Object invoke = method.invoke(target, objects);

                System.out.println("----------cglib log-----------");

                return invoke;
            }
        };

        enhancer.setCallback(methodInterceptor);

        // 代理对象
        Object o = enhancer.create();
        return o ;
    }

}
